<?php

if(!defined('OT_ROOT')) {
	exit('Access Denied');
}



class Users{

	// 写入session和cookies
	public static function SetCookies($name, $value, $expTime=0){
		if (strpos('|userID|username|userpwd|usermail|usercall|scoreStr|recomId|','|'. $name .'|') !== false){
			$_SESSION[OT_SiteID . $name] = $value;
		}
		if (strpos('|userID|username|usercall|scoreStr|recomId|userInfo|','|'. $name .'|') !== false){
			if (is_null($expTime)){ $expTime = 0; }
			setcookie(OT_SiteID . $name, $value, $expTime, '', '', false, true);
		}
	}

	// 获取session和cookies
	public static function GetCookies($name){
		$str = '';
		if ($name != 'userInfo'){
			$str = @$_SESSION[OT_SiteID . $name];
		}
		if (empty($str) && strpos('|userID|username|usercall|scoreStr|recomId|userInfo|','|'. $name .'|') !== false){
			$str = @$_COOKIE[OT_SiteID . $name];
		}
		return $str;
	}

	// 获取GetCookies中的userID，并格式化为数值
	public static function UserID(){
		return intval(self::GetCookies('userID'));
	}

	// 获取GetCookies中的username，并过滤掉非法字符
	public static function Username(){
		return self::FilterStr(self::GetCookies('username'));
	}

	// 获取GetCookies中的usercall，并过滤掉非法字符
	public static function Usercall(){
		return self::FilterStr(self::GetCookies('usercall'));
	}


	// 检测用户名
	public static function CheckUsername($method,$username){
		global $DB,$userSysArr;

		if (strlen($username) != strlen(Str::RegExp($username,'sql'))){
			$alertStr='用户名含特殊符号';
			if ($method == 'send'){
				die('<script language="javascript">parent.$id("usernameStr").innerHTML="<span class=font2_2>'. $alertStr .'</span>";</script>');
			}elseif ($method == 'write'){
				die('<font color="red">'. $alertStr .'</font>');
			}elseif ($method == 'check'){
				die('<script language="javascript">alert("'. $alertStr .'");history.back(-1);</script>');
			}elseif ($method == 'ajax'){
				die('alert("'. $alertStr .'");regWaitTime=0;HiddenMengceng();');
			}
		}

		$nameTemp = iconv("UTF-8", "GBK//IGNORE", $username);
		$nameNum = strlen($nameTemp);
		if ($nameNum > 16 || $nameNum < 4){
			$alertStr='长度在4到16字节，当前长度'. $nameNum .'字节。一个汉字占2字节';
			if ($method == 'send'){
				die('<script language="javascript">parent.$id("usernameStr").innerHTML="<span class=font2_2>'. $alertStr .'</span>";</script>');
			}elseif ($method == 'write'){
				die('<font color="red">'. $alertStr .'</font>');
			}elseif ($method == 'check'){
				die('<script language="javascript">alert("'. $alertStr .'");history.back(-1);</script>');
			}elseif ($method == 'ajax'){
				die('alert("'. $alertStr .'");regWaitTime=0;HiddenMengceng();');
			}
		}

		if (empty($userSysArr)){ $userSysArr = Cache::PhpFile('userSys'); }
		if ($userSysArr['US_regBadWord']!=''){
			$username = strtolower($username);
			$badWordArr = explode('|',strtolower($userSysArr['US_regBadWord']));
			foreach ($badWordArr as $str){
				if ($str != ''){
					$alertStr='用户名中含禁止注册关键词（'. $str .'）';
					if (strpos($username,$str) !== false){
						if ($method == 'send'){
							die('<script language="javascript">parent.$id("usernameStr").innerHTML="<span class=font2_2>'. $alertStr .'</span>";</script>');
						}elseif ($method == 'write'){
							die('<font color="red">'. $alertStr .'</font>');
						}elseif ($method == 'check'){
							die('<script language="javascript">alert("'. $alertStr .'");history.back(-1);</script>');
						}elseif ($method == 'ajax'){
							die('alert("'. $alertStr .'");regWaitTime=0;HiddenMengceng();');
						}
					}
				}
			}
		}

		$checkexe = $DB->QueryParam('select UE_ID from '. OT_dbPref .'users where UE_username=?',array($username));
			if ($checkexe->fetch()){
				$alertStr='该用户名已存在，请更换';
				if ($method == 'send'){
					die('<script language="javascript">parent.$id("usernameStr").innerHTML="<span class=font2_2>'. $alertStr .'</span>";</script>');
				}elseif ($method == 'write'){
					die('<font color="red">'. $alertStr .'</font>');
				}elseif ($method == 'check'){
					die('<script language="javascript">alert("'. $alertStr .'");history.back(-1);</script>');
				}elseif ($method == 'ajax'){
					die('alert("'. $alertStr .'");regWaitTime=0;HiddenMengceng();');
				}
			}else{
				$alertStr='恭喜！该用户名未被占用';
				if ($method == 'send'){
					die('<script language="javascript">parent.$id("usernameStr").innerHTML="<span class=font4_2>'. $alertStr .'</span>"</script>');
				}elseif ($method == 'write'){
					die('<font color="green">'. $alertStr .'</font>');
				}
			}
		unset($checkexe);

	}


	// 检测邀请人
	public static function CheckRecomUser($method,$username){
		global $DB;

		if (strlen($username) != strlen(Str::RegExp($username,'sql'))){
			JS::AlertEnd('邀请人不能含特殊符号');
		}

		$nameTemp = iconv("UTF-8", "GBK//IGNORE", $username);
		$nameNum = strlen($nameTemp);
		if ($nameNum > 16 || $nameNum < 4){
			JS::AlertEnd('邀请人长度在4到16字节，当前长度'. $nameNum .'字节。一个汉字占2字节');
		}

		$checkexe = $DB->QueryParam('select UE_ID from '. OT_dbPref .'users where UE_username=?',array($username));
			if ($checkexe->fetch()){
				JS::AlertEnd('恭喜！该邀请人存在');
			}else{
				JS::AlertEnd('该邀请人不存在，请重新输入');
			}
		unset($checkexe);

	}


	// 检测通用会员登录状态和返回会员信息
	public static function CheckLoginState($modeStr,$addiField,$addiEvent=''){
		global $userSysArr;
		if (empty($userSysArr)){ $userSysArr = Cache::PhpFile('userSys'); }

		$userRow = Users::Open('get',',UE_username,UE_state,UE_authStr'. $addiField,'',$judUserErr);
			if ((! $userRow) || $judUserErr != ''){
				JS::ModeDeal($modeStr,false,'请先登录，该功能需要登录才能使用。（'. $judUserErr .'）', Users::SysUrl('login','&force=1&isBack=1'));
			}
			if ($userRow['UE_state'] == 0){
				JS::ModeDeal($modeStr,false,'您尚未审核通过，该功能无法使用。', Users::SysUrl('login','&force=1&isBack=1'));
			}
			// 检测用户邮箱、手机号是否需要强制验证
			AreaApp::UserTixing($userRow['UE_authStr'], $userSysArr, 1, 'js');
		
		return $userRow;
	}


	// 过滤字符串（正则表达式）
	public static function FilterStr($str){
		$str = $str .'';
		$newStr = strtr($str,array(
		' '=>'', ','=>'', '.'=>'', ':'=>'', ';'=>'', '"'=>'', '"'=>'', '`'=>'', '~'=>'', '?'=>'', '!'=>'', '@'=>'', '#'=>'', "\$"=>'', '%'=>'', '^'=>'', '&'=>'', '*'=>'', '<'=>'', '>'=>'', '('=>'', ')'=>'', '+'=>'', '-'=>'', '/'=>'', '='=>'', "\\"=>'', '{'=>'', '}'=>'', '0xbf27'=>''
		));
		
		return $newStr;
	}


	// 获取会员信息
	public static function Get(){
		global $userSysArr;

		if (empty($userSysArr)){ $userSysArr = Cache::PhpFile('userSys'); }

		$userID		= intval(@$_SESSION[OT_SiteID .'userID']);
		$username	= self::FilterStr(@$_SESSION[OT_SiteID .'username']);
		$userpwd	= @$_SESSION[OT_SiteID .'userpwd'];
		$usermail	= @$_SESSION[OT_SiteID .'usermail'];
		$usercall	= self::FilterStr(@$_SESSION[OT_SiteID .'usercall']);
		$scoreStr	= @$_SESSION[OT_SiteID .'scoreStr'];
		if ($userID>0 && $username!='' && $userpwd!=''){
			$userInfoStr = $userID ."\t". $username ."\t". $userpwd ."\t". $usermail ."\t". $usercall ."\t". $scoreStr;
		}else{
			$userInfoStr = self::GetCookies('userInfo');
			$userInfoStr = Encrypt::PwdDecode($userInfoStr,$userSysArr['US_loginKey']);
		}
		return $userInfoStr;
	}


	// 更新会员信息
	public static function Update($user_ID,$user_name,$user_pwd,$user_mail,$user_call,$user_scoreStr,$user_expTime=0){
		global $userSysArr;

		if (empty($userSysArr)){ $userSysArr = Cache::PhpFile('userSys'); }

		$_SESSION[OT_SiteID .'userID']			= $user_ID;
		$_SESSION[OT_SiteID .'username']		= $user_name;
		$_SESSION[OT_SiteID .'userpwd']			= $user_pwd;
		$_SESSION[OT_SiteID .'usermail']		= $user_mail;
		$_SESSION[OT_SiteID .'usercall']		= $user_call;
		$_SESSION[OT_SiteID .'userScoreStr']	= $user_scoreStr;
		if ($user_expTime == 0){ $user_expTime = null; }
		self::SetCookies('userID', $user_ID, $user_expTime);
		self::SetCookies('username', $user_name, $user_expTime);
		self::SetCookies('usercall', $user_call, $user_expTime);
		self::SetCookies('userInfo', Encrypt::PwdEncode($user_ID ."\t". $user_name ."\t". $user_pwd ."\t". $user_mail ."\t". $user_call ."\t". $user_scoreStr,$userSysArr['US_loginKey']), $user_expTime);
	//	echo("alert('". GetCookies("username") ."|". GetCookies("userInfo") ."');");
	}


	// 清空会员信息
	public static function Delete(){
		$_SESSION[OT_SiteID .'userID']			= 0;
		//	$_SESSION[OT_SiteID .'username']	= null;
		$_SESSION[OT_SiteID .'userpwd']			= ' ';
		$_SESSION[OT_SiteID .'usermail']		= ' ';
		$_SESSION[OT_SiteID .'usercall']		= ' ';
		$_SESSION[OT_SiteID .'userScoreStr']	= ' ';
		self::SetCookies('username',' ');
		self::SetCookies('userInfo',' ');
	}



	// 打开用户表
	// modeStr：模式（jud:有存在返回true，否则返回false；alertBack:如不存在提示并返回）
	// sqlStr：附加打开的用户字段,要以","号开头（如：,UE_username,UE_realname）
	// whereStr：子条件句
	public static function Open($modeStr,$sqlStr,$whereStr,&$judErrStr){
		global $DB,$userSysArr;

		if (empty($userSysArr)){ $userSysArr = Cache::PhpFile('userSys'); }

		if ($modeStr == ''){ $modeStr='alertBack'; }

		$userID			= 0;
		$username		= '';
		$userpwd		= '';
		$userInfoStr	= self::Get();
		$userArr		= explode("\t",$userInfoStr);
		if (count($userArr)>=4){
			$userID		= intval($userArr[0]);
			$username	= self::FilterStr($userArr[1]);
			$userpwd	= self::FilterStr($userArr[2]);
		}

		$userexe = $DB->query('select UE_ID'. $sqlStr .' from '. OT_dbPref .'users where UE_ID='. $userID .' and UE_userpwd='. $DB->ForStr($userpwd) . $whereStr);
		if (! $row = $userexe->fetch()){
			$judErrStr = JS::ModeDeal($modeStr,false,'请先登录', Users::SysUrl('login','&force=1&isBack=1'));
				if ($judErrStr != ''){
					return $row;
				}
		}else{
			if ($userSysArr['US_exitMinute'] > 0){
				$userExitNewTime = time();
				$userExitOldTime = intval(@$_SESSION['userExitOldTime']);
				if ($userExitOldTime + $userSysArr['US_exitMinute'] * 60 < $userExitNewTime){
					self::Delete();
					$judErrStr = JS::ModeDeal($modeStr,false,'您超过'. $userSysArr['US_exitMinute'] .'分钟没动静，请重新登录。','deal.php?mudi=exit');
						if ($judErrStr != ''){
							return $row;
						}
				}else{
					$_SESSION['userExitOldTime'] = $userExitNewTime;
				}
			}

			if ($modeStr == 'jud'){
				$judErrStr = true;
				return $row;
			}

			// 检查会员在线状态
			$OT_userIP	= self::GetIp();
			$OT_signCode = self::GetSignCode();
			$onlinerec = $DB->query("select UO_ID,UO_time,UO_computerCode,UO_ip from ". OT_dbPref ."userOnline where UO_userID=". $row["UE_ID"] ." and UO_ip=". $DB->ForStr($OT_userIP) ."");
				if ($row2 = $onlinerec->fetch()){
					$record = array();
					$record['UO_time']			= TimeDate::Get();
					$record['UO_computerCode']	= $OT_signCode;
					$record['UO_ip']			= $OT_userIP;
					$DB->UpdateParam('userOnline',$record,'UO_ID='. $row2['UO_ID']);
				}else{
					if ($userSysArr['US_loginMode'] == 1){
						$judErrStr = JS::ModeDeal($modeStr,false,'登录记录不存在，可能您账号被别人登录或者IP改变，请重新登录。','users_deal.php?mudi=onlineClear');
							if ($judErrStr != ''){
								return $row;
							}
					}
				}
			unset($onlinerec);

			return $row;
		}
	}


	// 快捷登录模式注册
	public static function AutoReg($apiType,$apiId,$realname=''){
		global $DB,$systemArr,$userSysArr;

		if (strpos('|qq|weibo|weixin|wxmp|taobao|alipay|','|'. $apiType .'|') === false){ return array('res'=>false,'note'=>'类型错误（'. $apiType .'）'); }

		if (empty($systemArr)){ $systemArr = Cache::PhpFile('system'); }
		if (empty($userSysArr)){ $userSysArr = Cache::PhpFile('userSys'); }

		$username	= $apiType .'_'. substr($apiId,-8) . OT::RndChar(1);

		if ($userSysArr['US_isUserSys'] == 0){ return array('res'=>false,'note'=>'会员系统已关闭'); }
		if ($userSysArr['US_isReg'] == 0){ return array('res'=>false,'note'=>'会员注册已关闭'); }

		if (AppQuan::JudReg()){ return array('res'=>false,'note'=>'会员系统需要注册邀请码注册，请联系管理员处理'); }

		$userpwd = $answer = $mail = '';

		$userpwd = md5($apiId . OT::RndChar(5));
		$userpwdKey		= OT::RndChar(5);
		$userpwd		= md5(md5($userpwd) . $userpwdKey);
		$answerKey		= OT::RndChar(5);
		$answer			= md5(md5($answer) . $answerKey);

		$todayTime		= TimeDate::Get();
		$userIP			= Users::GetIp();
		$signCode		= Users::GetSignCode();

		// IP黑名单
		$checkIpexe = $DB->QueryParam("select UI_ID from ". OT_dbPref ."userIp where UI_type='bad' and UI_ip=?",array($userIP));
			if ($checkIpexe->fetch()){ return array('res'=>false,'note'=>'该IP已被拉入黑名单，如有问题请与管理员联系。'); }
		unset($checkIpexe);

		$allowRegTime = TimeDate::Add('n',$userSysArr['US_againRegMinute']*(-1),$todayTime);
		if ($userSysArr['US_againRegMinute']>0){
			$checkIpexe = $DB->QueryParam("select UI_ID from ". OT_dbPref ."userIp where UI_type='reg' and UI_ip=? and UI_time>?",array($userIP,$allowRegTime));
				if ($checkIpexe->fetch()){ return array('res'=>false,'note'=>'每'. $userSysArr['US_againRegMinute'] .'分钟内只能注册一次，请'. $userSysArr['US_againRegMinute'] .'分钟后再注册。'); }
			unset($checkIpexe);
		}
		
		if ($userSysArr['US_isRegAudit'] == 1){
			$alertStr = '\n您当前状态[待审核],需要管理员的审核。';
		}else{
			$alertStr = '';
		}

		if ($userSysArr['US_isRegAudit'] == 1){
			$userState = 0;
			$isRecomScore = 0;
		}else{
			$userState = 1;
			$isRecomScore = 1;
		}
		
		$regScoreArr = Users::ScoreArr('reg');

		$record = array();
		$record['UE_time']			= $todayTime;
		$record['UE_loginTime']		= $todayTime;
		$record['UE_regType']		= $apiType;
		$record['UE_regIP']			= $userIP;
		$record['UE_apiStr']		= '|'. $apiType .'::'. $apiId .':1|';
		$record['UE_username']		= $username;
		$record['UE_userpwd']		= $userpwd;
		$record['UE_groupID']		= $userSysArr['US_regGroupID'];
		$record['UE_userKey']		= $userpwdKey;
		$record['UE_question']		= '';
		$record['UE_answer']		= $answer;
		$record['UE_answerKey']		= $answerKey;
		$record['UE_face']			= '';
		$record['UE_realname']		= $realname;
		$record['UE_score1']		= $regScoreArr['US_score1'];
		$record['UE_score2']		= $regScoreArr['US_score2'];
		$record['UE_score3']		= $regScoreArr['US_score3'];
		$record['UE_state']			= $userState;

		$judRes = $DB->InsertParam('users',$record);
		if ($judRes){
			$alertRes = '成功';
			$userID = $DB->GetOne('select max(UE_ID) from '. OT_dbPref .'users');

			if (AppUserScore::IsAdd($regScoreArr['US_score1'], $regScoreArr['US_score2'], $regScoreArr['US_score3'])){
				$scoreArr = array();
				$scoreArr['UM_userID']		= $userID;
				$scoreArr['UM_username']	= $username;
				$scoreArr['UM_type']		= 'reg';
				$scoreArr['UM_score1']		= $regScoreArr['US_score1'];
				$scoreArr['UM_score2']		= $regScoreArr['US_score2'];
				$scoreArr['UM_score3']		= $regScoreArr['US_score3'];
				$scoreArr['UM_remScore1']	= $regScoreArr['US_score1'];
				$scoreArr['UM_remScore2']	= $regScoreArr['US_score2'];
				$scoreArr['UM_remScore3']	= $regScoreArr['US_score3'];
				$scoreArr['UM_note']		= '自动授权注册成功';
				AppUserScore::AddData($scoreArr);
			}

			if ($userSysArr['US_againRegMinute'] > 0){
				$DB->QueryParam("delete from ". OT_dbPref ."userIp where UI_type='reg' and UI_time<?",array($allowRegTime));
				$DB->QueryParam("insert into ". OT_dbPref ."userIp (UI_type,UI_time,UI_date,UI_dataID,UI_userID,UI_ip,UI_computerCode) values('reg',?,?,0,?,?,?)",array($todayTime, TimeDate::Get('date'), $userID, $userIP, $signCode));
			}

			$_SESSION['userExitOldTime']= time();
			$_SESSION['userRegTime']	= time();

			// 把会员信息写入COOKIES
			Users::Update($userID,$username,$userpwd,$mail,$realname,$regScoreArr['US_score1'] .'|'. $regScoreArr['US_score2'] .'|'. $regScoreArr['US_score3']);

			Users::Online($todayTime,$userID,$signCode,$userIP);

			// 是否发送注册邮件
			if ($userSysArr['US_isAuthMail'] == 1 && AppMail::Jud() && strlen($mail) > 0){
				$resArr = AppMail::ContentSend('reg', $mail, $userID, $username);
				/* if (! $resArr['res']){
					$alertStr .= '\n邮件发送失败，原因：'. $resArr['note'];
				} */
			}

			// 是否发送注册短信
			// if ($userSysArr['US_isAuthPhone'] == 1 && AppPhone::Jud() && strlen($phone) > 0){
			// 	$resArr = AppPhone::ContentSend('reg', $phone, $userID, $username, array('user'=>$username));
				/* if (! $resArr['res']){
					$alertStr .= '\n短信发送失败，原因：'. $resArr['note'];
				} */
			// }

			$ipInfoArr = OT::GetIpInfoArr($userIP, '');
			$ipAlertStr	= '（用户IP：'. $userIP .'，用户地址：'. $ipInfoArr['address'] .'）';

			// 发送通知信息
			if ($userState == 1){
				AreaApp::MessageSend('reg1', Users::RegTypeCN($apiType) .'授权注册会员“'. $username .'”，状态[已审核]'. $ipAlertStr .'。【'. $todayTime .'】');
			}else{
				AreaApp::MessageSend('reg0', '『审核』'. Users::RegTypeCN($apiType) .'授权注册会员“'. $username .'”，状态[待审核]，需要管理员审核'. $ipAlertStr .'。【'. $todayTime .'】');
			}

			return array('res'=>true,'note'=>'授权注册成功.','userID'=>$userID,'username'=>$username);
		}else{
			return array('res'=>false,'note'=>'注册失败！请检查是否有信息填写不规范。');
		}
	}

	// 更新会员在线状态
	public static function Online($userTime,$user_ID,$signCode,$userIP){
		global $DB;

		$record = array();
		$record['UO_time']			= $userTime;
		$record['UO_userID']		= $user_ID;
		$record['UO_computerCode']	= $signCode;
		$record['UO_ip']			= $userIP;

		$onlinerec = $DB->query("select UO_time,UO_userID,UO_computerCode,UO_ip from ". OT_dbPref ."userOnline where UO_userID=". $user_ID);
		if ($onlinerec->fetch()){
			$DB->UpdateParam('userOnline',$record,'UO_userID='. $user_ID);
		}else{
			$DB->InsertParam('userOnline',$record);
		}
		unset($onlinerec);
	}

	// 获取积分名称数组
	public static function ScoreNameArr($userSysArr = null){
		if (empty($userSysArr)){ $userSysArr = Cache::PhpFile('userSys'); }
		$retArr = array();
		$retArr['is1']			= 1;
		$retArr['is2']			= $userSysArr['US_isScore2'];
		$retArr['is3']			= $userSysArr['US_isScore3'];
		$retArr['name1']		= $userSysArr['US_score1Name'];
		$retArr['nameNum1']		= '积分1';
		$retArr['nameFull1']	= '积分1（'. $userSysArr['US_score1Name'] .')';
		$retArr['css1']			= '';

		if ($userSysArr['US_isScore2'] == 1){
			$retArr['name2']		= $userSysArr['US_score2Name'];
			$retArr['nameNum2']		= '积分2';
			$retArr['nameFull2']	= '积分2（'. $userSysArr['US_score2Name'] .')';
			$retArr['css2']			= '';
		}else{
			$retArr['name2']		= '<span style="color:#ccc; text-decoration:line-through;">'. $userSysArr['US_score2Name'] .'</span>';
			$retArr['nameNum2']		= '<span style="color:#ccc; text-decoration:line-through;">积分2</span>';
			$retArr['nameFull2']	= '<span style="color:#ccc; text-decoration:line-through;">积分2（'. $userSysArr['US_score2Name'] .')</span>';
			$retArr['css2']			= 'display:none;';
		}

		if ($userSysArr['US_isScore3'] == 1){
			$retArr['name3']		= $userSysArr['US_score3Name'];
			$retArr['nameNum3']		= '积分3';
			$retArr['nameFull3']	= '积分3（'. $userSysArr['US_score3Name'] .')';
			$retArr['css3']			= '';
		}else{
			$retArr['name3']		= '<span style="color:#ccc; text-decoration:line-through;">'. $userSysArr['US_score3Name'] .'</span>';
			$retArr['nameNum3']		= '<span style="color:#ccc; text-decoration:line-through;">积分3</span>';
			$retArr['nameFull3']	= '<span style="color:#ccc; text-decoration:line-through;">积分3（'. $userSysArr['US_score3Name'] .')</span>';
			$retArr['css3']			= 'display:none;';
		}

		return $retArr;
	}


	// 更新会员积分
	public static function UpdateScore($userID, $type, $score1=0, $score2=0, $score3=0, $sqlArr=array(), $mode=''){
		global $DB;

		switch ($type){
			case 'add': case '+':		$type = '+';	break;
			case 'cut': case '-':		$type = '-';	break;
			default :		die('UpdateScore 目的不明确.');
		}

		if ($score1 >= 0){
			$score1Str = $type . $score1;
		}else{
			if ($type == '+'){ $score1Str = $score1; }else{ $score1Str = '+'. abs($score1); }
		}
		if ($score2 >= 0){
			$score2Str = $type . $score2;
		}else{
			if ($type == '+'){ $score2Str = $score2; }else{ $score2Str = '+'. abs($score2); }
		}
		if ($score3 >= 0){
			$score3Str = $type . $score3;
		}else{
			if ($type == '+'){ $score3Str = $score3; }else{ $score3Str = '+'. abs($score3); }
		}

		$dataArr = array();
		$dataArr['UE_score1']		= 'UE_score1'. $score1Str;
		$dataArr['UE_score2']		= 'UE_score2'. $score2Str;
		$dataArr['UE_score3']		= 'UE_score3'. $score3Str;

		return $DB->Update('users', array_merge($dataArr,$sqlArr), 'UE_ID='. $userID, $mode);

	}


	public static function RegTypeCN($num){
		switch ($num){
			case 'qq':			return 'QQ';
			case 'weibo':		return '新浪微博';
			case 'weixin':		return '微信';
			case 'wxmp':		return '微信公众号';
			case 'taobao':		return '淘宝';
			case 'alipay':		return '支付宝';
			case 'web':			return '网站';
			case 'back':		return '后台';
			case 'dede':		return '织梦';
			case 'tianren':		return '天人';
			case 'emlog':		return 'emlog';
			case 'wordpress':	return 'wordpress';
			default:			return '['. $num .']';
		}
	}

	// 获得用户IP地址
	public static function GetIp(){
		if (getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')){
			$userIP = getenv('HTTP_CLIENT_IP');
		}elseif (getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')){
			$userIP = getenv('HTTP_X_FORWARDED_FOR');
		}elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')){
			$userIP = $_SERVER['REMOTE_ADDR'];
		}
		/*
		}elseif (getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')){
			$userIP = getenv('REMOTE_ADDR');
		*/
		$userIP = addslashes($userIP);
		if ($userIP == '::1'){
			$userIP = '127.0.0.1';
		}else{
			@preg_match("/[\d\.]{7,15}/", $userIP, $userIpArr);
			$userIP = $userIpArr[0] ? $userIpArr[0] : 'unknown';
			unset($userIpArr);
		}
		return $userIP;
	}

	// 获取电脑识别符
	public static function GetSignCode($userIP=null){
		if (empty($userIP)){ $userIP = self::GetIp(); }
		if (isset($_SERVER['HTTP_USER_AGENT'])){
			$userAgent = $_SERVER['HTTP_USER_AGENT'];
		}else{
			$userAgent = '';
		}
		return md5(OT_SiteID . $userIP . $userAgent);	// session_id()
	}

	// 读取积分信息
	public static function ScoreArr($typeStr){
		global $DB;

		$scoreexe = $DB->query('select US_score1,US_score2,US_score3,US_dayNum,US_strLen from '. OT_dbPref ."userScore where US_type='". $typeStr ."'");
		if (! $row = $scoreexe->fetch()){
			JS::AlertEnd('会员积分没找到，类型：'. $typeStr);
		}
		return $row;
	}


	// 会员上传图片删除
	public static function DelFile($whereStr){
		global $DB;

		$delrec=$DB->query('select UF_ID,UF_oss,UF_type,UF_name,UF_otherImgStr from '. OT_dbPref .'userFile where '. $whereStr);
		while ($row = $delrec->fetch()){
			if (in_array($row['UF_oss'],AreaApp::OssNameArr())){
				$ossJud = AreaApp::OssDel($row['UF_oss'], $row['UF_name']);
				/* if (! $ossJud){
					JS::AlertEnd($row['UF_oss'] .' 文件“'. $row['UF_name'] .'”删除失败');
				} */
			}else{
				$delPath = StrInfo::FilePath($row['UF_type'], $row['UF_name']);
				File::Del($delPath);
				$otherImgArr = explode(',',$row['UF_otherImgStr']);
				for ($i=0; $i<count($otherImgArr); $i++){
					$delPath = StrInfo::FilePath($row['UF_type'], $otherImgArr[$i]);
					File::Del($delPath);
				}
			}
		}
		
		return $DB->query('delete from '. OT_dbPref .'userFile where '. $whereStr);
	}
	
	// 添加会员操作记录
	public static function AddLog($userID, $username, $note, $adminNote='', $logArr=array()){
		global $DB;

		$userIP	= Users::GetIp();
		$ipInfoArr = OT::GetIpInfoArr($userIP, '');

		if (Is::Mobile()){ $mode = '手机端'; }else{ $mode = '电脑端'; }

		$record=array();
		$record['UL_time']		= TimeDate::Get();
		$record['UL_userID']	= $userID;
		$record['UL_username']	= $username;
		$record['UL_ip']		= $userIP;
		$record['UL_ipCN']		= $ipInfoArr['address'];
		$record['UL_note']		= '【'. $mode .'】'. $note;
		$record['UL_adminNote']	= $adminNote;

		return $DB->InsertParam('userLog',$record);
	}
	
	// 添加会员积分
	public static function AddScore($type, $userID, $dataID, $infoID=0, $note='', $content=''){
		global $DB;

		$retArr = array('res'=>false, 'note'=>'', 'errStr'=>'');
		if ($userID <= 0){
			$retArr['errStr'] = '非会员';
			return $retArr;
		}

		$typeCN		= StrCN::ScoreType($type);
		$getScoreArr = Users::ScoreArr($type);
			if ($getScoreArr['US_score1'] <= 0 && $getScoreArr['US_score2'] <= 0 && $getScoreArr['US_score3'] <= 0){
				$retArr['errStr'] = '未设置'. $typeCN .'积分';
				return $retArr;
			}
		$isGetScore	= 1;
		$getScore1	= $getScoreArr['US_score1'];
		$getScore2	= $getScoreArr['US_score2'];
		$getScore3	= $getScoreArr['US_score3'];
		$typeStr	= '';
		$type1ID	= 0;
		$type2ID	= 0;
		$type3ID	= 0;
		$num		= 0;

		if ($getScoreArr['US_strLen'] > 0 && strlen($content) < $getScoreArr['US_strLen']){
			$retArr['errStr'] = '评论内容长度（'. strlen($content) .'）低于规定'. $getScoreArr['US_strLen'] .'字符';
			$retArr['note'] = '无积分，'. $retArr['errStr'];
			return $retArr;
		}
		if ($getScoreArr['US_dayNum'] > 0){
			$todayDate = TimeDate::Get('date');
			switch ($type){
				case 'newsAdd':
					// 添加文章
					$time = $DB->GetOne('select IF_time from '. OT_dbPref .'info where IF_ID='. $dataID);
					$todayDate = TimeDate::Get('date', $time);
					$num = $DB->GetOne('select count(1) from '. OT_dbPref .'info where IF_userID='. $userID .' and IF_isGetScore=1 and IF_time>='. $DB->ForTime($todayDate .' 00:00:00') .' and IF_time<='. $DB->ForTime($todayDate .' 23:59:59'));
					break;
			
				case 'infoMessage':
					// 评论
					$time = $DB->GetOne('select IM_time from '. OT_dbPref .'infoMessage where IM_ID='. $dataID);
					$todayDate = TimeDate::Get('date', $time);
					$num = $DB->GetOne('select count(1) from '. OT_dbPref .'infoMessage where IM_userID='. $userID .' and IM_isGetScore=1 and IM_time>='. $DB->ForTime($todayDate .' 00:00:00') .' and IM_time<='. $DB->ForTime($todayDate .' 23:59:59'));
					break;
			
				case 'message':
					// 留言
					$time = $DB->GetOne('select MA_time from '. OT_dbPref .'message where MA_ID='. $dataID);
					$todayDate = TimeDate::Get('date', $time);
					$num = $DB->GetOne('select count(1) from '. OT_dbPref .'message where MA_userID='. $userID .' and MA_isGetScore=1 and MA_time>='. $DB->ForTime($todayDate .' 00:00:00') .' and MA_time<='. $DB->ForTime($todayDate .' 23:59:59'));
					break;
			
				case 'bbsWriteAdd':
					// 论坛发帖
					$time = $DB->GetOne('select BD_time from '. OT_dbPref .'bbsData where BD_ID='. $dataID);
					$todayDate = TimeDate::Get('date', $time);
					$num = $DB->GetOne('select count(1) from '. OT_dbPref .'bbsData where BD_userID='. $userID .' and BD_isGetScore=1 and BD_time>='. $DB->ForTime($todayDate .' 00:00:00') .' and BD_time<='. $DB->ForTime($todayDate .' 23:59:59'));
					break;
			
				case 'bbsReplyAdd':
					// 帖子回复
					$time = $DB->GetOne('select BR_time from '. OT_dbPref .'bbsReply where BR_ID='. $dataID);
					$todayDate = TimeDate::Get('date', $time);
					$num = $DB->GetOne('select count(1) from '. OT_dbPref .'bbsReply where BR_userID='. $userID .' and BR_isGetScore=1 and BR_time>='. $DB->ForTime($todayDate .' 00:00:00') .' and BR_time<='. $DB->ForTime($todayDate .' 23:59:59'));
					break;
			
				default :
					$retArr['errStr'] = $todayDate . $typeCN .'次数未知（'. $type .'）';
					$retArr['note'] = '无积分，'. $retArr['errStr'];
					return $retArr;
					break;
			}
			if ($num >= $getScoreArr['US_dayNum']){
				$retArr['errStr'] = $todayDate . $typeCN .'得分次数（'. $num .'）已达规定限制，请明天再来';	// '. $getScoreArr['US_dayNum'] .'次
				$retArr['note'] = '无积分，'. $retArr['errStr'];
				return $retArr;
			}
		}

		$dataArr = array();
		switch ($type){
			case 'newsAdd':
				$dataArr['IF_isGetScore']	= $isGetScore;
				$dataArr['IF_getScore1']	= $getScore1;
				$dataArr['IF_getScore2']	= $getScore2;
				$dataArr['IF_getScore3']	= $getScore3;
				$DB->UpdateParam('info', $dataArr, 'IF_ID='. $dataID);
				break;

			case 'infoMessage':
				$dataArr['IM_isGetScore']	= $isGetScore;
				$dataArr['IM_getScore1']	= $getScore1;
				$dataArr['IM_getScore2']	= $getScore2;
				$dataArr['IM_getScore3']	= $getScore3;
				$DB->UpdateParam('infoMessage', $dataArr, 'IM_ID='. $dataID);

				$infoRow = $DB->GetRow('select IF_theme,IF_typeStr,IF_type1ID,IF_type2ID,IF_type3ID from '. OT_dbPref .'info where IF_ID='. $infoID);
					$typeStr	= $infoRow['IF_typeStr'];
					$type1ID	= $infoRow['IF_type1ID'];
					$type2ID	= $infoRow['IF_type2ID'];
					$type3ID	= $infoRow['IF_type3ID'];
				if (strlen($note) == 0){
					$note		= '评论文章['. Info::InfoTypeCN($type1ID, $type2ID, $type3ID) .']《'. $infoRow['IF_theme'] .'》，内容：'. Str::LimitChar($content,30);
				}
				break;

			case 'message':
				$dataArr['MA_isGetScore']	= $isGetScore;
				$dataArr['MA_getScore1']	= $getScore1;
				$dataArr['MA_getScore2']	= $getScore2;
				$dataArr['MA_getScore3']	= $getScore3;
				$DB->UpdateParam('message',$dataArr,'MA_ID='. $dataID);

				if (strlen($note) == 0){
					$note	= '发表留言：'. Str::LimitChar($content,30);
				}
				break;

			case 'bbsWriteAdd':
				$dataArr['BD_isGetScore']	= $isGetScore;
				$dataArr['BD_getScore1']	= $getScore1;
				$dataArr['BD_getScore2']	= $getScore2;
				$dataArr['BD_getScore3']	= $getScore3;
				$DB->UpdateParam('bbsData',$dataArr,'BD_ID='. $dataID);

				if (strlen($note) == 0){
					$note	= '发布帖子《'. Str::LimitChar($content,30) .'》';
				}
				break;

			case 'bbsReplyAdd':
				$dataArr['BR_isGetScore']	= $isGetScore;
				$dataArr['BR_getScore1']	= $getScore1;
				$dataArr['BR_getScore2']	= $getScore2;
				$dataArr['BR_getScore3']	= $getScore3;
				$DB->UpdateParam('bbsReply',$dataArr,'BR_ID='. $dataID);

				if (strlen($note) == 0){
					$note	= '回复帖子：'. Str::LimitChar(Str::RegExp($content,'html'),30);
				}
				break;

			default :
				die('AddScore type类型目标不明确');
				break;
		}

		// 更新积分
		Users::UpdateScore($userID, '+', $getScore1, $getScore2, $getScore3);

		// 会员积分记录 插件
		if (AppUserScore::IsAdd($getScore1, $getScore2, $getScore3)){
			$userRow = $DB->GetRow('select UE_username,UE_score1,UE_score2,UE_score3 from '. OT_dbPref .'users where UE_ID='. $userID);
			$scoreArr = array();
			$scoreArr['UM_userID']		= $userID;
			$scoreArr['UM_username']	= $userRow['UE_username'];
			$scoreArr['UM_type']		= $type;
			$scoreArr['UM_dataID']		= $dataID;
			$scoreArr['UM_typeStr']		= $typeStr;
			$scoreArr['UM_type1ID']		= $type1ID;
			$scoreArr['UM_type2ID']		= $type2ID;
			$scoreArr['UM_type3ID']		= $type3ID;
			$scoreArr['UM_score1']		= $getScore1;
			$scoreArr['UM_score2']		= $getScore2;
			$scoreArr['UM_score3']		= $getScore3;
			$scoreArr['UM_remScore1']	= $userRow['UE_score1'];	//  + $getScore1
			$scoreArr['UM_remScore2']	= $userRow['UE_score2'];	//  + $getScore2
			$scoreArr['UM_remScore3']	= $userRow['UE_score3'];	//  + $getScore3
			$scoreArr['UM_note']		= $note;
			AppUserScore::AddData($scoreArr);
		}

		$retArr['res'] = true;
		$retArr['note'] = '今日第'. ($num + 1) .'次获得'. $typeCN .'积分';
		return $retArr;
	}
	
	// 检测插件会员登录状态
	public static function CheckPulgin($type, $addiField='', $mode=''){
		global $userSysArr;
		if (empty($userSysArr)){ $userSysArr = Cache::PhpFile('userSys'); }

		switch ($type){
			case 'taokeOrder': case 'taokeOrderJiesuan':
				if (strlen($addiField) == 0){
					$addiField = ',UE_money,UE_score1,UE_score2,UE_score3';
				}
				break;
		}

		if (in_array($mode, array('new','href','alertHref'))){
			$modeStr = 'alertHref';
		}elseif (in_array($mode, array('back','alertBack'))){
			$modeStr = 'alertBack';
		}elseif (in_array($mode, array('close','alertClose'))){
			$modeStr = 'alertClose';
		}else{
			$modeStr = 'alert';
		}

		$userRow = Users::Open('get',',UE_username,UE_state,UE_authStr'. $addiField,'',$judUserErr);
			if ((! $userRow) || $judUserErr != ''){
				JS::ModeDeal($modeStr,false,'请先登录，该功能需要登录才能使用。（'. $judUserErr .'）', Users::SysUrl('login','&force=1&isBack=1'));
			}
			if (! in_array($type,array('diyPay')) ){
				if ($userRow['UE_state'] == 0){
					JS::ModeDeal($modeStr,false,'您尚未审核通过，该功能无法使用。', Users::SysUrl('login','&force=1&isBack=1'));
				}
				// 检测用户邮箱、手机号是否需要强制验证
				AreaApp::UserTixing($userRow['UE_authStr'], $userSysArr, 1, 'js');
			}

		return $userRow;
	}
	
	// 判断是否使用新会员系统路径
	public static function JudNewSys(){
		global $userSysArr;
		if (empty($userSysArr)){ $userSysArr = Cache::PhpFile('userSys'); }

		if ($userSysArr['US_isOldSys'] == 0){
			return true;
		}else{
			return false;
		}
	}

	// 根据访问端显示对应内容
	public static function NewOldShow($newStr, $oldStr){
		if (self::JudNewSys()){
			return $newStr;
		}else{
			return $oldStr;
		}
	}

	// 会员系统地址路径
	public static function SysUrl($type, $addiStr='', $webPathPart='', $mode='pc'){
		if (defined('OT_ucROOT')){
			$indexUrl = $webPathPart .'index.php';
			$mainUrl = $webPathPart .'usersCenter.php';
			$mudiName = 'm';
		}elseif ( self::JudNewSys() ){
			// 新会员系统地址
			if ($mode == 'wap'){
				$indexUrl = $webPathPart .'users/';
				$mainUrl = $webPathPart .'users/usersCenter.php';
			}else{
				$indexUrl = $webPathPart .'wap/users/';
				$mainUrl = $webPathPart .'wap/users/usersCenter.php';
			}
			$mudiName = 'm';
		}else{
			// 旧会员系统地址
			$indexUrl = $webPathPart .'users.php';
			$mainUrl = $webPathPart .'usersCenter.php';
			$mudiName = 'mudi';
		}

		if (in_array($type, array('reg','login','missPwd'))){
			$goUrl = $indexUrl .'?'. $mudiName .'='. $type;
		}elseif (strlen($type) == 0){
			$goUrl = $indexUrl;
		}else{
			$goUrl = $mainUrl .'?'. $mudiName .'='. $type;
		}

		return $goUrl . $addiStr;
	}

	// 左上角会员菜单
	public static function TopMenuWeb(){
		global $userSysArr,$userApiArr;

		require(OT_ROOT .'cache/php/userApi.php');
		if (empty($userSysArr)){ $userSysArr = Cache::PhpFile('userSys'); }

		if ($userSysArr['US_isLogin'] == 1){
			$username = Users::Username();	// die('【'. $username .'】');
			$usercall = Users::Usercall();
			if ($username == ''){
				$missPwdStr = '';
				if ($userSysArr['US_isMissPwd'] == 1){
					$missPwdStr = '
						<div class="left" style="padding:0 6px;">/</div>
						<div id="uebox_miss" class="left" style="padding-right:12px;"><a href="'. Users::SysUrl('missPwd','','./') .'" class="font2_1" >忘记密码</a></div>
						';
				}
				echo('
				<div id="uebox_img" class="left">'. str_replace('[backURL]', '', @$userApiArr['imgTop'] .'') .'</div>
				<div id="uebox_login" class="left"><a href="'. Users::SysUrl('login','','./') .'" class="font2_1" >登录</a></div>
				<div class="left" style="padding:0 6px;">/</div>
				<div id="uebox_reg" class="left"><a href="'. Users::SysUrl('reg','','./') .'" class="font2_1" >注册</a></div>		
				'. $missPwdStr);
			}else{
				if (strlen($usercall)>0){ $showName = $usercall; }else{ $showName = $username; }
				echo('
				<div class="left font1_1">
					<div id="uebox_welcome" class="left">欢迎您，<b>'. $showName .'</b></div>
					<div id="uebox_center" class="left" style="padding-left:20px;"><a href="'. Users::SysUrl('userCenter','','./') .'" class="font2_1" >[会员中心]</a></div>
					'. AppQiandao::UminiMenu() .'
					'. UcNews::UminiMenu() .'
					<div id="uebox_exit" class="left" style="padding:0 12px 0 8px;"><a href="javascript:void(0);" class="font2_1" onclick=\'UserExit();return false;\' >[退出]</a></div>
				</div>
				');
			}
		}
	}

	// 首页会员登录窗口
	public static function HomeLoginWeb(){
		global $userSysArr,$userApiArr;

		require(OT_ROOT .'cache/php/userApi.php');
		if (empty($userSysArr)){ $userSysArr = Cache::PhpFile('userSys'); }

		if ($userSysArr['US_isLogin'] == 1){
			$tplSysArr = Cache::PhpFile('tplSys');

			$username = Users::Username();
			$usercall = Users::Usercall();
			if ($username == ''){
				if (strlen(trim(''. Str::RegExp($tplSysArr['TS_homeLoginStr1'],'html'))) >= 3){
					echo($tplSysArr['TS_homeLoginStr1']);
				}else{
					$missPwdStr = '';
					if ($userSysArr['US_isMissPwd'] == 1){
						$missPwdStr = '
							<div id="homeLogin_miss"><a href="'. Users::SysUrl('missPwd') .'" class="font2_1" >【忘记密码】</a></div>
							';
					}
					echo('
					<div id="homeLogin_login"><a href="'. Users::SysUrl('login') .'" class="font2_1" >【会员登录】</a></div>
					<div id="homeLogin_reg"><a href="'. Users::SysUrl('reg') .'" class="font2_1" >【会员注册】</a></div>		
					'. $missPwdStr .'
					<div id="homeLogin_img">'. str_replace(array('class="left uebox_api"','[backURL]'), array('class="homeLogin_api"',''), @$userApiArr['imgTop'] .'') .'</div>
					');
				}
			}else{
				if (strlen(trim(''. Str::RegExp($tplSysArr['TS_homeLoginStr2'],'html'))) >= 3){
					echo($tplSysArr['TS_homeLoginStr2']);
				}else{
					if (strlen($usercall)>0){ $showName = $usercall; }else{ $showName = $username; }
					echo('
					<div class="font1_1">
						<div id="homeLogin_welcome">欢迎您，<b>'. $showName .'</b></div>
						<div id="homeLogin_center"><a href="'. ($userSysArr['US_isOldSys'] == 0 ? './wap/users/usersCenter.php' : './usersCenter.php') .'" class="font2_1" >[会员中心]</a></div>
						'. AppQiandao::UminiMenu('home') .'
						'. UcNews::UminiMenu('home') .'
						<div id="homeLogin_exit"><a href="javascript:void(0);" class="font2_1" onclick=\'UserExit();return false;\' >[会员退出]</a></div>
					</div>
					');
				}
			}
		}
	}

}
?>